import React, {Suspense} from 'react';
import {Switch, Route, Redirect} from 'react-router-dom';
import RoutesConfig from 'config/route.config';
import Loading from 'components/Loading';
import {findRoutes} from 'utils/routes';

interface BaseProps {
    pathKey: string;
}

interface RenderComp {
    path: string;
    component?: any;
    redirect?: any;
    map?: any;
}

const renderComp: any = (config: RenderComp) => {
    return (
        <Suspense fallback={<Loading />}>
            <Switch>
                {config.map((item: any, index: number) => {
                    const {path, redirect, component} = item;
                    if (redirect) {
                        return (
                            <Route
                                key={index + ''}
                                path={path}
                                exact={true}
                                component={() => <Redirect to={redirect} />}
                            />
                        );
                    } else if (component) {
                        return <Route key={index + ''} path={item.path} exact={index === 0} component={component} />;
                    } else {
                        return <Loading />;
                    }
                })}
            </Switch>
        </Suspense>
    );
};

export default (props: BaseProps) => {
    const {pathKey} = props;
    if (pathKey === 'root') {
        return renderComp(RoutesConfig);
    } else {
        return renderComp(findRoutes(RoutesConfig, pathKey));
    }
};
